package com.rpc.learn.transport.support;

import com.rpc.learn.transport.dto.RpcResponse;
import com.rpc.learn.transport.exception.RemoteException;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * unprocessed requests by the server.
 *
 * @author shuang.kou
 * @createTime 2020年06月04日 17:30:00
 */
public class UnprocessedRequests {
    private static final Map<String, CompletableFuture<RpcResponse>> UNPROCESSED_RESPONSE_FUTURES = new ConcurrentHashMap<>();

    public void put(String requestId, CompletableFuture<RpcResponse> future) {
        UNPROCESSED_RESPONSE_FUTURES.put(requestId, future);
    }

    public void complete(RpcResponse rpcResponse) {
        CompletableFuture<RpcResponse> future = UNPROCESSED_RESPONSE_FUTURES.remove(rpcResponse.getRequestId());
        if (null != future) {
            if(rpcResponse.getData() instanceof RemoteException) {
                future.completeExceptionally((RemoteException)rpcResponse.getData());
            }else {
                future.complete(rpcResponse);
            }
        } else {
            throw new IllegalStateException();
        }
    }
}
